import { PageContainer } from '@ant-design/pro-layout';
import { Button, DatePicker, DatePickerProps, Form, Input, message, Modal, Popconfirm, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';

import styles from '@/pages/CommonLess/List.less';
import formStyles from '@/pages/CommonLess/Form.less';
import { updateTemplate, deleteTemplate, pageTemplate } from '@/services/template/template';

interface pageProps {
  actionTable: string
}

const page: React.FC<pageProps> = (props) => {
  const { actionTable } = props
  const { RangePicker } = DatePicker

  const search = React.useRef<any>()
  const [isVisible, setIsVisible] = useState<boolean>(false)
  const [isUpdate, setIsUpdate] = useState<boolean>(true)
  const [row, setRow] = useState<API.Template>({})
  const [data, setData] = useState<API.Template[]>([])
  const [pagination, setPagination] = useState<API.Pagination>({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const [pageContent, setPageContent] = useState<API.Page>({})
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])


  // 初始化数据
  useEffect(() => {
    let isUnmount = false;
    const getApps = async () => {
      let result = await pageTemplate(pageContent);
      if (result && result.data.records && !isUnmount) {
        // 初始化表格数据
        setData(result.data.records)
        // 初始化分页
        setPagination({
          ...pagination,
          total: result.data.total
        })
      }
    }
    getApps()
    return () => {
      isUnmount = true
    }
  }, [actionTable])

  // 刷新表格
  const refreshTable = async() => {
    let tempPageContent = {...pageContent, current: 1}
    let result = await pageTemplate(tempPageContent);
    if (result && result.data.records){
      setSelectedRowKeys([]);
      setData(result.data.records)
      setPageContent(tempPageContent)
      setPagination({
        ...pagination,
        current: 1,
        total: result.data.total
      })
    }
  }

  // 跳转页面或者改变页面大小
  const paginationChange = async(record: any) => {
    setPagination({
      current: record.current,
      pageSize: record.pageSize,
      total: record.total
    })
    let tempPageContent = {
      ...pageContent,
      current: record.current,
      pageSize: record.pageSize
    }
    setPageContent(tempPageContent)
    let result = await pageTemplate(tempPageContent)
    if(result && result.data.records){
      setData(result.data.records)
    }
  }

  // 查找内容
  const searchSubmit = async () => {
    if(search.current){
      let searchContent = search.current.state.value;
      // 修改分页查询内容
      let tempPageContent = {...pageContent, current: 1, searchContent: searchContent}
      setPagination({...pagination, current: 1})
      setPageContent(tempPageContent)
      let result = await pageTemplate(tempPageContent)
      if(result && result.data.records){
        setData(result.data.records)
      }else{
        message.error("请输入正确的关键词")
      }
    }
  }

  // 添加
  const onFinish = async (value: any) => {
    let result = await updateTemplate(value);
    if(result && result.code === 200){
      setIsVisible(false);
      await refreshTable();
      message.success("添加成功")
      setRow({});
    }else{
      message.error("添加失败")
    }
  };

  // 更新
  const onUpdate = async (value: any) => {
    let result = await updateTemplate(value)
    if(result && result.code === 200){
      setIsVisible(false);
      await refreshTable();
      message.success("修改成功")
      setRow({});
    }else{
      message.error("修改失败")
    }
  }

  // 取消
  const onCancel = () => {
    setRow({});
    setIsVisible(false);
  }

  // 删除单个
  const deleteData = async (record: API.Template) => {
    let params = {"ids": record.id}
    let result = await deleteTemplate(params)
    if(result && result.code === 200){
      message.success("删除成功")
      await refreshTable()
    }else{
      message.error("删除失败")
    }
  }

  // 删除勾选
  const deleteIds = async () => {
    if (selectedRowKeys.length === 0) {
      message.error("至少选择一条数据")
      return
    }
    let ids = selectedRowKeys.join(",");
    let params = {"ids": ids}
    let result = await deleteTemplate(params)
    if(result && result.code === 200){
      message.success("删除成功")
      await refreshTable()
    }else{
      message.error("删除失败")
    }
  }

  // 改变选择
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 选择时间
  const onDateChange = (record: any) => {
    let startTime = record[0].format('YYYY-MM-DD')
    let endTime = record[1].format('YYYY-MM-DD')
    setPageContent({...pageContent, startTime: startTime, endTime: endTime});
  }

  // 表格字段和操作
  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 100,
      render: (text: any, record: any, index: number) => (
        <Space>
          <a
            onClick={() => {
              setIsUpdate(true);
              setIsVisible(true);
              setRow(record);
            }}
          >
            编辑
          </a>
          <Popconfirm
            title="是否删除?"
            onConfirm={()=>{
              deleteData(record)
            }}
            onCancel={() => {}}
            okText="删除"
            cancelText="取消"
          >
            <a>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ]
  return (
    <PageContainer>
      <div className={styles.header}>
        <Space>
          <div>关键字</div>
          <Input
            maxLength={20}
            ref={search}
            onPressEnter={searchSubmit}
            allowClear
            placeholder="姓名"
          />
          <Button type="primary" onClick={searchSubmit}>
            搜索
          </Button>
          <RangePicker onChange={onDateChange} />
        </Space>
        <Space>
          <Popconfirm
            title={`是否删除${selectedRowKeys.length}条记录?`}
            onConfirm={()=>{
              deleteIds()
            }}
            onCancel={() => {}}
            okText="删除"
            cancelText="取消"
          >
            <Button
              type="primary"
            >
              删除
            </Button>
          </Popconfirm>
          <Button
            type="primary"
            onClick={() => {
              setIsVisible(true);
              setIsUpdate(false);
            }}
          >
            新建
          </Button>
        </Space>
      </div>
      <div>
        <Table
          bordered
          rowKey="id"
          dataSource={data}
          columns={columns}
          pagination={{
            pageSizeOptions: ['10', '50', '100', '200'],
            showTotal: total => `共${total}条记录`,
            showSizeChanger: true,
            ...pagination
          }}
          onChange={paginationChange}
          rowSelection={{
            selectedRowKeys,
            onChange: onSelectChange,
          }}
        />
      </div>
      <Modal
        visible={isVisible}
        maskClosable={false}
        title={isUpdate ? '编辑数据' : '新建数据'}
        destroyOnClose
        // onOk={finish}
        onCancel={() => {
          onCancel();
        }}
        footer={null}
      >
        <Form
          className={formStyles.Form}
          {...{
            labelCol: { span: 5 },
            wrapperCol: { span: 19 },
          }}
          onFinish={isUpdate ? onUpdate : onFinish }
        >
          <Form.Item label="编号" name="id" initialValue={row.id}>
            <Input disabled={true} />
          </Form.Item>
          <Form.Item label="姓名" name="name" initialValue={row.name}>
            <Input />
          </Form.Item>
          <Space className={formStyles.Space}>
            <Button
              type="primary"
              onClick={() => {
                onCancel()
              }}
            >
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              {isUpdate ? '更改' : '保存'}
            </Button>
          </Space>
        </Form>
      </Modal>
    </PageContainer>
  )
}

export default page;
